<?php
if (!defined('SMF'))
	die('Hacking attempt...');
	
global $smcFunc, $txt, $scripturl, $user_info;
global $dbtables;
global $allow_genesis_destroy, $sofa_on, $allow_ibank;

// Verify user login, if CheckLogin() returns false return to the calling script/function
if (CheckLogin() == false)
	return;
	
include("combat.php");

// Pull player info into $playerinfo.
$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_ships}
	WHERE user_id = {int:user_id}
	LIMIT 1',
	array(
		'db_ships' => $dbtables['ships'],
		'user_id' => $user_info['id'],
	)
);
$playerinfo = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);

// Pull sector info into $sectorinfo.
$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_universe}
	WHERE sector_id = {int:sector_id}',
	array(
		'db_universe' => $dbtables['universe'],
		'sector_id' => $playerinfo['sector']
	)
);
$sectorinfo = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);

// Pull planet information into $planetinfo.
$planet_id = (isset($_GET['planet_id'])) ? $_GET['planet_id'] : '';
$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_planets}
	WHERE planet_id = {int:planet_id}',
	array(
		'db_planets' => $dbtables['planets'],
		'planet_id' => $planet_id
	)
);
if ($smcFunc['db_num_rows']($result) > 0)
	$planetinfo = $smcFunc['db_fetch_assoc']($result);
else
	$planetinfo = '';
$smcFunc['db_free_result']($result);

// Check for a planet command
if (isset($_GET['command']))
	$command = $_GET['command'];
elseif (isset($_POST['command']))
	$command = $_POST['command'];
else
	$command = '';

srand((double)microtime()*1000000);

// Make sure the planet exists before beginning
if (!empty($planetinfo))
{
	// If the player sector has changed somehow, update their information
	if ($playerinfo['sector'] != $planetinfo['sector_id'])
	{
		if ($playerinfo['on_planet'] == 'Y')
		{
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET on_planet = "N"
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
		}
		
		BigTitle('');
		echo '<p>', $txt['bnt_planet_none'], '</p>';
		return;
	}
	
	// Insert hidden planet id for use with all planet commands
	echo '<input id="planet_id" type="hidden" value="', $planet_id, '">';
	
	// Display the planet information for an unowned, defeated planet
	if (($planetinfo['owner'] == 0  || $planetinfo['defeated'] == 'Y') && $command != 'capture')
	{
		DisplayPlanetTitle($planetinfo);
		// Show empty planet menu
		echo '
					<div id="planet_menu_frame">
						<div id="planet_menu_content">
							<h4>', $txt['bnt_planet_title'], '</h4>
							<ul>
								<li><span class="planet_menu_button" title="command=capture">', ucfirst($txt['bnt_planet_capture1']), '</span></li>
							</ul>
						</div>
					</div>';
					
		// Planet resources on empty planets are viewable by everyone for now, so feed it the same $playerinfo
		DisplayPlanetResources($planetinfo, $playerinfo, $playerinfo);	
					
		return;
	}
	
	// Planet has an owner, find out who it is
	if ($planetinfo['owner'] != 0)
	{
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_ships}
			WHERE ship_id = {int:owner}',
			array(
				'db_ships' => $dbtables['ships'],
				'owner' => $planetinfo['owner']
			)
		);
		$ownerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
	}
	
	// If there is no planet command . . .
	if (empty($command))
	{
		// Display owner menu
		if ($planetinfo['owner'] == $playerinfo['ship_id'] || ($planetinfo['corp'] == $playerinfo['team'] && $playerinfo['team'] > 0))
		{
			DisplayPlanetTitle($planetinfo);
			DisplayOwnerMenu($planet_id, $planetinfo, $playerinfo);
			DisplayPlanetResources($planetinfo, $playerinfo, $playerinfo);
		}
		// Display the visitor menu.
		else
		{
			DisplayPlanetTitle($planetinfo);
			DisplayVistorMenu($planet_id, $planetinfo, $ownerinfo, $playerinfo);
			DisplayPlanetResources($planetinfo, $ownerinfo, $playerinfo);
		}
	}
	// Player owns planet and there is a command
	elseif ($planetinfo['owner'] == $playerinfo['ship_id'] || ($planetinfo['corp'] == $playerinfo['team'] && $playerinfo['team'] > 0))
	{
		switch ($command)
		{
			// Change the planet sell options.
			case "sell":
				// Set the planet to sell
				if ($planetinfo['sells'] == "Y")
				{
					$commandresult = '<strong>' . $txt['bnt_planet_sellon'] . '</strong>';
					$update = $smcFunc['db_query']('', '
						UPDATE {raw:db_planets}
						SET sells = "N"
						WHERE planet_id = {int:planet_id}',
						array(
							'db_planets' => $dbtables['planets'],
							'planet_id' => $planet_id
						)
					);
				}
				// Set the planet to not sell
				else
				{
					$commandresult = '<strong>' . $txt['bnt_planet_selloff'] . '</strong>';
					$update = $smcFunc['db_query']('', '
						UPDATE {raw:db_planets}
						SET sells = "Y"
						WHERE planet_id = {int:planet_id}',
						array(
							'db_planets' => $dbtables['planets'],
							'planet_id' => $planet_id
						)
					);
				}
				DisplayPlanetTitle($planetinfo);
				DisplayOwnerMenu($planet_id, $planetinfo, $playerinfo, $commandresult);
				DisplayPlanetResources($planetinfo, $playerinfo, $playerinfo);
				continue;
				
			// Display planet rename menu.
			case "changename":
				// If confirm isn't set, display a dialog to rename the planet
				if (!isset($_GET['confirm']))
				{
					echo '
							<p><span class="planet_status_title">', $txt['bnt_name'], '</span><input id="planet_newname" name="planet_newname" type="text" size="10" length="25" value="', $planetinfo['name'],'" /></p>';
				}
				// Change the name
				else
				{
					// Get the new name
					$planet_newname = trim(strip_tags($_GET['planet_newname']));
					
					// Update planet with new name
					$update = $smcFunc['db_query']('', '
						UPDATE {raw:db_planets}
						SET name = {string:new_name}
						WHERE planet_id = {int:planet_id}',
						array(
							'db_planets' => $dbtables['planets'],
							'new_name' => $planet_newname,
							'planet_id' => $planet_id
						)
					);
					
					// Refresh planetinfo
					$result = $smcFunc['db_query']('', '
						SELECT *
						FROM {raw:db_planets}
						WHERE planet_id = {int:planet_id}',
						array(
							'db_planets' => $dbtables['planets'],
							'planet_id' => $planet_id
						)
					);
					$planetinfo = $smcFunc['db_fetch_assoc']($result);
					
					$commandresult =  $txt['bnt_planet_cname'] . ' <strong>' . $planetinfo['name'] . '</strong>';
					
					DisplayPlanetTitle($planetinfo);
					DisplayOwnerMenu($planet_id, $planetinfo, $playerinfo, $commandresult);
					DisplayPlanetResources($planetinfo, $playerinfo, $playerinfo);
					continue;
				}
				continue;
		
			// Player lands on the planet, update the database.
			case "land":	
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET on_planet = "Y",
						planet_id = {int:planet_id}
					WHERE ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'ship_id' => $playerinfo['ship_id'],
						'planet_id' => $planet_id,
					)
				);
				
				// Refresh $playerinfo.
				$result = $smcFunc['db_query']('', '
					SELECT *
					FROM {raw:db_ships}
					WHERE user_id = {int:user_id}
					LIMIT 1',
					array(
						'db_ships' => $dbtables['ships'],
						'user_id' => $user_info['id'],
					)
				);
				$playerinfo = $smcFunc['db_fetch_assoc']($result);
				$smcFunc['db_free_result']($result);
				
	
				// Update background image
				echo '
					<script type="text/javascript">
						$(document).ready(function(){
							$(".bnt_mainframe_display").css({\'background-image\':"url(\'" + smf_images_url + "/bnt/hubbleimages/hs-2003-22-a-full_jpg.jpg\')"});
						});
					</script>';
				
				$commandresult =  '<strong>' . $txt['bnt_planet_landed'] . '</strong>';
				
				DisplayPlanetTitle($planetinfo);
				DisplayOwnerMenu($planet_id, $planetinfo, $playerinfo, $commandresult);
				DisplayPlanetResources($planetinfo, $playerinfo, $playerinfo);
				continue;
				
			// Player leaves the planet, update the database.
			// Added planet_id = 0.  JAB 122908
			case "leave":
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET on_planet = "N",
						planet_id = 0
					WHERE ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'ship_id' => $playerinfo['ship_id'],
						'planet_id' => $planet_id,
					)
				);
				
				// Refresh $playerinfo.
				$result = $smcFunc['db_query']('', '
					SELECT *
					FROM {raw:db_ships}
					WHERE user_id = {int:user_id}
					LIMIT 1',
					array(
						'db_ships' => $dbtables['ships'],
						'user_id' => $user_info['id'],
					)
				);
				$playerinfo = $smcFunc['db_fetch_assoc']($result);
				$smcFunc['db_free_result']($result);
				
				// Update background image
				echo '
					<script type="text/javascript">
						$(document).ready(function(){
							$(".bnt_mainframe_display").css({\'background-image\':"url(\'" + smf_images_url + "/bnt/bgoutspace1.gif\')"});
						});
					</script>';

				
				$commandresult =  '<strong>' . $txt['bnt_planet_left'] . '</strong>';
				
				DisplayPlanetTitle($planetinfo);
				DisplayOwnerMenu($planet_id, $planetinfo, $playerinfo, $commandresult);
				DisplayPlanetResources($planetinfo, $playerinfo, $playerinfo);
				continue;

			// Display planetary transfer menu.
			case "transfer":
				DisplayPlanetTitle($planetinfo);
				require("planet_transfer.php");
				
				$transfer_request = (isset($_GET['transfer_request'])) ? $_GET['transfer_request'] : '';
				
				if ($transfer_request == '')
					DisplayTransferForm($playerinfo,$planetinfo);
				else
					ProcessTransferRequest($playerinfo, $planetinfo);
					
				continue;
		
			// Display planetary base menu.
			case "base":
				global $base_ore, $base_organics, $base_goods, $base_credits;
				
				if ($planetinfo['ore'] >= $base_ore && $planetinfo['organics'] >= $base_organics && $planetinfo['goods'] >= $base_goods && $planetinfo['credits'] >= $base_credits)
				{
					// Create the base.
					//
					// DOUBLECHECK - this says the player left the planet . . . but we don't update his status?
					//
					echo $txt['bnt_planet_left'], '<br><br>';
					$update = $smcFunc['db_query']('', '
						UPDATE {raw:db_planets}
						SET base = "Y",
							ore = {int:planetinfo_ore}  - {int:base_ore},
							organics = {int:planetinfo_organics} - {int:base_organics},
							goods = {int:planetinfo_goods}  - {int:base_goods},
							credits = {int:planetinfo_credits}  - {int:base_credits} 
						WHERE planet_id = {int:planet_id}',
						array(
							'db_planets' => $dbtables['planets'],
							'planet_id' => $planet_id,
							'planetinfo_ore' => $planetinfo['ore'],
							'base_ore' => $base_ore,
							'planetinfo_organics' => $planetinfo['organics'],
							'base_organics' => $base_organics,
							'planetinfo_goods' => $planetinfo['goods'],
							'base_goods' => $base_goods,
							'planetinfo_credits' => $planetinfo['credits'],
							'base_credits' => $base_credits,
						)
					);
					
					// Update user turns.
					$update = $smcFunc['db_query']('', '
						UPDATE {raw:db_ships}
						SET turns = turns - 1,
							turns_used = turns_used + 1
						WHERE ship_id = {int:ship_id}',
						array(
							'db_ships' => $dbtables['ships'],
							'ship_id' => $playerinfo['ship_id']
						)
					);
					
					// Refresh planet information.
					$result = $smcFunc['db_query']('', '
						SELECT *
						FROM {raw:db_planets}
						WHERE planet_id = {int:planet_id}',
						array(
							'db_planets' => $dbtables['planets'],
							'planet_id' => $planet_id
						)
					);
					$planetinfo = $smcFunc['db_fetch_assoc']($result);
					$smcFunc['db_free_result']($result);
					
					// Notify user of base results.
					echo $txt['bnt_planet_bbuild'], '<br><br>';
					
					// Calculate ownership and notify player of results
					$ownership = calc_ownership($playerinfo['sector']);
					if (!empty($ownership))
						echo '<p>', $ownership, '<p>';
				}
				else
					echo $txt['bnt_planet_baseinfo'], '<br><br>';
				continue;
			
			// Player wishes to destroy the planet
			case "destroy":
				// Confirm first and make sure planet destroying is allowed
				if (!isset($_GET['confirm']) && $allow_genesis_destroy) 
				{
					if (empty($planetinfo['name']))
						$planetname = $txt['bnt_unnamed'] . ' ' . $txt['bnt_planet'];
					else
						$planetname = $planetinfo['name'];
				
					$txt['bnt_planet_destroy'] = str_replace("[planet]", '<strong>' . $planetname . '</strong>', $txt['bnt_planet_destroy']);
					$txt['bnt_planet_destroy'] = str_replace("[sector]", '<strong>' . $planetinfo['sector_id'] . '</strong>', $txt['bnt_planet_destroy']);
					echo '
						<p>', $txt['bnt_planet_destroy'], '</p>';
				} 
				elseif (isset($_GET['confirm']) && $allow_genesis_destroy) 
				{ 
					if ($playerinfo['dev_genesis'] > 0) 
					{
						$delete = $smcFunc['db_query']('', '
							DELETE FROM {raw:db_planets}
							WHERE planet_id = {int:planet_id}',
							array(
								'db_planets' => $dbtables['planets'],
								'planet_id' => $planet_id
							)
						); 
						
						$update = $smcFunc['db_query']('', '
							UPDATE {raw:db_ships}
							SET dev_genesis = dev_genesis - 1
							WHERE ship_id = {int:ship_id}',
							array(
								'db_ships' => $dbtables['ships'],
								'ship_id' => $playerinfo['ship_id']
							)
						);
						
						$update = $smcFunc['db_query']('', '
							UPDATE {raw:db_ships}
							SET on_planet = "N"
							WHERE planet_id = {int:planet_id}',
							array(
								'db_ships' => $dbtables['ships'],
								'planet_id' => $planet_id
							)
						);
						
						calc_ownership($playerinfo['sector']);
						
						// Planet is deleted, reload the main display
						include("main.php");
						
						UpdateTurns($playerinfo, $user_info);
					} 
					else
					{
						$commandresult = $txt['bnt_gns_nogenesis']; 
						
						DisplayPlanetTitle($planetinfo);
						DisplayOwnerMenu($planet_id, $planetinfo, $playerinfo, $commandresult);
						DisplayPlanetResources($planetinfo, $playerinfo, $playerinfo);					
					}
				}
				continue;
			
			// Change production percentages.
			case "productions":
				$porganics = intval(stripnum($_POST['porganics']));
				$pore = intval(stripnum($_POST['pore']));
				$pgoods = intval(stripnum($_POST['pgoods']));
				$penergy = intval(stripnum($_POST['penergy']));
				$pfighters = intval(stripnum($_POST['pfighters']));
				$ptorp = intval(stripnum($_POST['ptorp']));
				if ($porganics < 0.0 || $pore < 0.0 || $pgoods < 0.0 || $penergy < 0.0 || $pfighters < 0.0 || $ptorp < 0.0)
					echo $txt['bnt_planet_p_under'], '<br><br>';
				elseif(($porganics + $pore + $pgoods + $penergy + $pfighters + $ptorp) > 100.0)
					echo $txt['bnt_planet_p_over'], '<br><br>';
				else
				{
					$update = $smcFunc['db_query']('', '
						UPDATE {raw:db_planets}
						SET prod_ore = {int:pore},
							prod_organics = {int:porganics},
							prod_goods = {int:pgoods},
							prod_energy = {int:penergy},
							prod_fighters = {int:pfighters},
							prod_torp = {int:ptorp}
						WHERE planet_id = {int:planet_id}',
						array(
							'db_planets' => $dbtables['planets'],
							'planet_id' => $planet_id,
							'pore' => $pore,
							'porganics' => $porganics,
							'pgoods' => $pgoods,
							'penergy' => $penergy,
							'pfighters' => $pfighters,
							'ptorp' => $ptorp
						)
					);
					echo $txt['bnt_planet_p_changed'], '<br><br>';
				}
				continue;
				
		    default:
				echo $txt['bnt_command_no'], '<br>';
		}
	}
    // Player does not own planet and there is a command
	else
	{
		switch ($command)
		{
			// A visiting player would like to buy commidities from the planet
			case "buy":
				if ($planetinfo['sells'] == "Y")
				{
					global $ore_price, $ore_delta;
					global $organics_price, $organics_delta;
					global $goods_price, $goods_delta;
					global $energy_price, $energy_delta;
					
					$ore_price = ($ore_price + $ore_delta / 4);
					$organics_price = ($organics_price + $organics_delta / 4);
					$goods_price = ($goods_price + $goods_delta / 4);
					$energy_price = ($energy_price + $energy_delta / 4);
					
					DisplayPlanetTitle($planetinfo);
					echo '
						<script type="text/javascript">
							$(document).ready(function(){
								// Table sorting function
								$(".bnt_table").tablesorter({
									widgets: ["zebra"]
								});
							});
						</script>
						<table id="planet_trade_table" class="bnt_table" width="100%" cellspacing="1" cellpadding="1">
							<thead>
								<tr>
									<th>', $txt['bnt_commodity'], '</th>
									<th>', $txt['bnt_amount'], '</th>
									<th>', $txt['bnt_price'], '</th>
									<th>', $txt['bnt_buy'], '</th>
									<th>', $txt['bnt_cargo'], '</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>', $txt['bnt_ore'], '</td>
									<td>', Number($planetinfo['ore']), '</td>
									<td>', $ore_price, '</td>
									<td><input id="trade_ore" type="text" name="trade_ore" size="10" maxlength="20" value="0"></td>
									<td>', Number($playerinfo['ship_ore']), '</td>
								</tr>
								<tr>
									<td>', $txt['bnt_organics'], '</td>
									<td>', Number($planetinfo['organics']), '</td>
									<td>', $organics_price, '</td>
									<td><input id="trade_organics" type="text" name="trade_organics" size="10" maxlength="20" value="0"></td>
									<td>', Number($playerinfo['ship_organics']), '</td>
								</tr>
								<tr>
									<td>', $txt['bnt_goods'], '</td>
									<td>', Number($planetinfo['goods']), '</td>
									<td>', $goods_price, '</td>
									<td><input id="trade_goods" type="text" name="trade_goods" size="10" maxlength="20" value="0"></td>
									<td>', Number($playerinfo['ship_goods']), '</td>
								</tr>
								<tr>
									<td>', $txt['bnt_energy'], '</td>
									<td>', Number($planetinfo['energy']), '</td>
									<td>', $energy_price, '</td>
									<td><input id="trade_energy" type="text" name="trade_energy" size="10" maxlength="20" value="0"></td>
									<td>', Number($playerinfo['ship_energy']), '</td>
								</tr>
							</tbody>
						</table>
						<div id="planet_button_frame" title="command=trade"><span class="bnt_button ui-state-default ui-corner-all">', $txt['bnt_trade'], '</span></div>
						<div id="planet_button_frame" title=""><span class="bnt_button ui-state-default ui-corner-all">', $txt['bnt_planet_menu'], '</span></div>';
				}
				else
					echo '<p>', $txt['bnt_planet_not_selling'], '</p>';
				continue;
			
			// Initiate the visitors requested trade
			case "trade":
			
				global $inventory_factor;
				global $ore_price, $ore_delta, $ore_limit;
				global $organics_price, $organics_delta, $organics_limit;
				global $goods_price, $goods_delta, $goods_limit;
				global $energy_price, $energy_delta, $energy_limit;
			
				DisplayPlanetTitle($planetinfo);
				
				$trade_ore = (isset($_GET['trade_ore'])) ? $_GET['trade_ore'] : 0;
				$trade_organics = (isset($_GET['trade_organics'])) ? $_GET['trade_organics'] : 0;
				$trade_goods = (isset($_GET['trade_goods'])) ? $_GET['trade_goods'] : 0;
				$trade_energy = (isset($_GET['trade_energy'])) ? $_GET['trade_energy'] : 0;

				$trade_ore = round(abs($trade_ore));
				$trade_organics = round(abs($trade_organics));
				$trade_goods = round(abs($trade_goods));
				$trade_energy = round(abs($trade_energy));
				$ore_price = ($ore_price + $ore_delta / 4);
				$organics_price = ($organics_price + $organics_delta / 4);
				$goods_price = ($goods_price + $goods_delta / 4);
				$energy_price = ($energy_price + $energy_delta / 4);

				if ($planetinfo['sells'] == 'Y')
				{
					$cargo_exchanged = $trade_ore + $trade_organics + $trade_goods;

					$free_holds = NUM_HOLDS($playerinfo['hull']) - $playerinfo['ship_ore'] - $playerinfo['ship_organics'] - $playerinfo['ship_goods'] - $playerinfo['ship_colonists'];
					$free_power = NUM_ENERGY($playerinfo['power']) - $playerinfo['ship_energy'];
					$total_cost = ($trade_ore * $ore_price) + ($trade_organics * $organics_price) + ($trade_goods * $goods_price) + ($trade_energy * $energy_price);
					
					if ($free_holds < $cargo_exchanged)
						echo $txt['bnt_notenough_cargo'], ' <a href=', $scripturl, '?action=blacknova;sa=planet;planet_id=', $planet_id, '>', $txt['bnt_clickme'], '</a> ', $txt['bnt_toplanetmenu'], '<br><br>';
					elseif ($trade_energy > $free_power) 
						echo $txt['bnt_notenough_power'], ' <a href=', $scripturl, '?action=blacknova;sa=planet;planet_id=', $planet_id, '>', $txt['bnt_clickme'], '</a> ', $txt['bnt_toplanetmenu'], '<br><br>';
					elseif ($playerinfo['turns'] < 1)
						echo $txt['bnt_notenough_turns'], '<br><br>';
					elseif ($playerinfo['credits'] < $total_cost)
						echo $txt['bnt_notenough_credits'], '<br><br>';
					elseif ($trade_organics > $planetinfo['organics'])
						echo $txt['bnt_exceed_organics'], ' ';
					elseif ($trade_ore > $planetinfo['ore'])
						echo $txt['bnt_exceed_ore'], ' ';
					elseif ($trade_goods > $planetinfo['goods'])
						echo $txt['bnt_exceed_goods'], ' ';
					elseif ($trade_energy > $planetinfo['energy'])
						echo $txt['bnt_exceed_goods'], ' ';
					else
					{
						$total_cost = round($total_cost);
						echo '
							<div id="planet_trade_result">
								<p>', $txt['bnt_totalcost'], ': ', $total_cost, '</p>
								<p>', $txt['bnt_traded_ore'], ': ', $trade_ore, '</p>
								<p>', $txt['bnt_traded_organics'], ': ', $trade_organics, '</p>
								<p>', $txt['bnt_traded_goods'], ': ', $trade_goods, '</p>
								<p>', $txt['bnt_traded_energy'], ': ', $trade_energy, '</p>';
						
						// Update ship cargo and credits
						$update = $smcFunc['db_query']('', '
							UPDATE {raw:db_ships}
							SET credits = credits - {int:total_cost},
								ship_ore = ship_ore + {int:trade_ore},
								ship_organics = ship_organics + {int:trade_organics},
								ship_goods = ship_goods + {int:trade_goods},
								ship_energy = ship_energy + {int:trade_energy}
							WHERE ship_id = {int:ship_id}',
							array(
								'db_ships' => $dbtables['ships'],
								'ship_id' => $playerinfo['ship_id'],
								'total_cost' => $total_cost,
								'trade_ore' => $trade_ore,
								'trade_organics' => $trade_organics,
								'trade_goods' => $trade_goods,
								'trade_energy' => $trade_energy
							)
						);
						
						// Update planet resources.
						$update = $smcFunc['db_query']('', '
							UPDATE {raw:db_planets}
							SET credits = credits + {int:total_cost},
								ore = ore - {int:trade_ore},
								organics = organics - {int:trade_organics},
								goods = goods - {int:trade_goods},
								energy = energy - {int:trade_energy}
							WHERE planet_id = {int:planet_id}',
							array(
								'db_planets' => $dbtables['planets'],
								'planet_id' => $planet_id,
								'total_cost' => $total_cost,
								'trade_ore' => $trade_ore,
								'trade_organics' => $trade_organics,
								'trade_goods' => $trade_goods,
								'trade_energy' => $trade_energy
							)
						);
						
						echo '
								<p>', $txt['bnt_trade_complete'], '</p>
								<div id="planet_button_frame" title=""><span class="bnt_button ui-state-default ui-corner-all">', $txt['bnt_planet_menu'], '</span></div>
							</div>';
						
						UpdateTurns($playerinfo, $user_info);
						
						// Refresh player info into $playerinfo.
						$result = $smcFunc['db_query']('', '
							SELECT *
							FROM {raw:db_ships}
							WHERE user_id = {int:user_id}
							LIMIT 1',
							array(
								'db_ships' => $dbtables['ships'],
								'user_id' => $user_info['id'],
							)
						);
						$playerinfo = $smcFunc['db_fetch_assoc']($result);
						$smcFunc['db_free_result']($result);
						
						echo '
							<input id="ship_ore" type="hidden" value="', Number($playerinfo['ship_ore']), '">
							<input id="ship_organics" type="hidden" value="', Number($playerinfo['ship_organics']), '">
							<input id="ship_goods" type="hidden" value="', Number($playerinfo['ship_goods']), '">
							<input id="ship_energy" type="hidden" value="', Number($playerinfo['ship_energy']), '">
							<input id="ship_credits" type="hidden" value="', Number($playerinfo['credits']), '">
						';
					}
				}

				gen_score($planetinfo['owner']);
				continue;
			
			// Player wants to attack planet
			case "attack":
				if (empty($planetinfo['name']))
					$planetname = $txt['bnt_unnamed'] . ' ' . $txt['bnt_planet'];
				else
					$planetname = $planetinfo['name'];
				
				// If the player has not yet confirmed the attack, then we are going to display a dialog and get the content from here
				if (!isset($_GET['confirm']))
				{
					$txt['bnt_planet_attack'] = str_replace("[planet]", '<strong>' . $planetname . '</strong>', $txt['bnt_planet_attack']);
					$txt['bnt_planet_attack'] = str_replace("[sector]", '<strong>' . $planetinfo['sector_id'] . '</strong>', $txt['bnt_planet_attack']);
					echo '
							<p>', $txt['bnt_planet_attack'], '</p>';
				}
				// Initiate the attack, the player has confirmed
				else
				{
					DisplayPlanetTitle($planetinfo);
					planetcombat($playerinfo,$ownerinfo,$sectorinfo,$planetinfo);	
				}
				continue;
			
			// Player has confirmed boming run, proceed.
		    case ($command == "bomb" && $sofa_on == TRUE):
				if (empty($planetinfo['name']))
					$planetname = $txt['bnt_unnamed'] . ' ' . $txt['bnt_planet'];
				else
					$planetname = $planetinfo['name'];
			
				// If the player has not yet confirmed the attack, then we are going to display a dialog and get the content from here
				if (!isset($_GET['confirm']))
				{
					$txt['bnt_planet_sofa'] = str_replace("[planet]", $planetname, $txt['bnt_planet_sofa']);
					$txt['bnt_planet_sofa'] = str_replace("[sector]", $planetinfo['sector_id'], $txt['bnt_planet_sofa']);
					echo '
							<p>', $txt['bnt_planet_sofa'], '</p>';
				}
				// Initiate the attack, the player has confirmed
				else
				{
					DisplayPlanetTitle($planetinfo);
					planetbombing($playerinfo,$ownerinfo,$sectorinfo,$planetinfo);	
				}
				continue;
			
			// Display scan menu.
			case "scan":
				DisplayPlanetTitle($planetinfo);
				
				echo '
			<input id="planetcommand_scan" type="hidden" value="">';
				
				if ($playerinfo['turns'] < 1)
				{
					$commandstatus = '<p>' . $txt['bnt_plant_scn_turn'] . '</p>';
					DisplayVistorMenu($planet_id, $planetinfo, $ownerinfo, $playerinfo, $commandstatus);
					DisplayPlanetResources($planetinfo, $ownerinfo, $playerinfo);
					return;
				}
				
				// Determine per cent chance of success in scanning target ship - based on player's sensors and opponent's cloak.
				$success = (10 - $ownerinfo['cloak'] / 2 + $playerinfo['sensors']) * 5;
				if ($success < 5)
					$success = 5;
				if ($success > 95)
					$success = 95;
				
				// If scan fails - inform both player and target.
				$roll = rand(1, 100);
				if ($roll > $success)
				{
					playerlog($ownerinfo['ship_id'], LOG_PLANET_SCAN_FAIL, "$planetinfo[name]|$playerinfo[sector]|$playerinfo[character_name]");
					
					$commandstatus = $txt['bnt_planet_noscan'];
					DisplayVistorMenu($planet_id, $planetinfo, $ownerinfo, $playerinfo, $commandstatus);
					DisplayPlanetResources($planetinfo, $ownerinfo, $playerinfo);
					
					UpdateTurns($playerinfo, $user_info);
				
					return;
				}
	
				//  If scan was successful . . .
				if ($roll < $success)
				{
					playerlog($ownerinfo['ship_id'], LOG_PLANET_SCAN, "$planetinfo[name]|$playerinfo[sector]|$playerinfo[character_name]");
					// Scramble results by scan error factor.
					// Planets currently have no cloak, so set this to 1 for now
					// Previously was $targetinfo['cloak']
					$sc_error = SCAN_ERROR($playerinfo['sensors'], 1);
	
					// Begin to display the output
					DisplayVistorMenu($planet_id, $planetinfo, $ownerinfo, $playerinfo);
				
					echo '
				<div id="planet_status_frame">
					<div class="overlay"></div>
					<div id="planet_status_content">
						<h4>', $txt['bnt_planet_status'], '</h4>
						<ul>
							<li><span class="planet_status_title">', $txt['bnt_planet_owner'], '</span><span class="planet_status_data">', $ownerinfo['character_name'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_planet_base'], '</span><span class="planet_status_data">', $planetinfo['base'] == 'Y' ? $txt['bnt_yes'] : $txt['bnt_no'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_planet_selling'], '</span><span class="planet_status_data">', $planetinfo['sells'] == 'Y' ? $txt['bnt_yes'] : $txt['bnt_no'], '</span></li>';
				
					// Determine scan results for amount of credits on planet.					
					$roll = rand(1, 100);
					if ($roll < $success)
					{
						$sc_planet_credits = Number(round($planetinfo['credits'] * $sc_error / 100));
						echo '
									<li><span class="planet_status_title">', $txt['bnt_credits'], '</span><span class="planet_status_data"><span class="scan_success">', $sc_planet_credits, '</span></span></li>';
					}
					else
						echo '		
									<li><span class="planet_status_title">', $txt['bnt_credits'], '</span><span class="planet_status_data"><span class="scan_failure">', $txt['bnt_planet_scanfailed'], '</span></span></li>';
									
					// Determine scan results for amount of colonists on planet.					
					$roll = rand(1, 100);
					if ($roll < $success)
					{
						$sc_planet_colonists = Number(round($planetinfo['colonists'] * $sc_error / 100));
						echo '
									<li><span class="planet_status_title">', $txt['bnt_colonists'], '</span><span class="planet_status_data"><span class="scan_success">', $sc_planet_colonists, '</span></span></li>';
					}
					else
						echo '		
									<li><span class="planet_status_title">', $txt['bnt_colonists'], '</span><span class="planet_status_data"><span class="scan_failure">', $txt['bnt_planet_scanfailed'], '</span></span></li>';
									
					// Determine scan results for amount of fighters on planet.					
					$roll = rand(1, 100);
					if ($roll < $success)
					{
						$sc_planet_fighters = Number(round($planetinfo['fighters'] * $sc_error / 100));
						echo '
									<li><span class="planet_status_title">', $txt['bnt_fighters'], '</span><span class="planet_status_data"><span class="scan_success">', $sc_planet_fighters, '</span></span></li>';
					}
					else
						echo '		
									<li><span class="planet_status_title">', $txt['bnt_fighters'], '</span><span class="planet_status_data"><span class="scan_failure">', $txt['bnt_planet_scanfailed'], '</span></span></li>';
									
					// Determine scan results for amount of torps on planet.					
					$roll = rand(1, 100);
					if ($roll < $success)
					{
						$sc_planet_torps = Number(round($planetinfo['torps'] * $sc_error / 100));
						echo '
									<li><span class="planet_status_title">', $txt['bnt_torps'], '</span><span class="planet_status_data"><span class="scan_success">', $sc_planet_torps, '</span></span></li>';
					}
					else
						echo '		
									<li><span class="planet_status_title">', $txt['bnt_torps'], '</span><span class="planet_status_data"><span class="scan_failure">', $txt['bnt_planet_scanfailed'], '</span></span></li>';

					// See if the player can scan who is on the planet.
					$result = $smcFunc['db_query']('', '
						SELECT *
						FROM {raw:db_ships}
						WHERE on_planet = "Y"
						AND planet_id = {raw:planet_id}',
						array(
							'db_ships' => $dbtables['ships'],
							'planet_id' => $planet_id
						)
					);
					
					while ($row = $smcFunc['db_fetch_assoc']($result))       
					{    
						$success = SCAN_SUCCESS($playerinfo['sensors'], $row['cloak']);
						
						if($success < 5)
							$success = 5;
						if($success > 95)
							$success = 95;
							
						$roll = rand(1, 100);
						if ($roll < $success)
							echo '
									<li><span class="planet_status_title">', $txt['bnt_ships'], '</span><span class="planet_status_data"><span class="scan_success">', $row['character_name'], '</span></span></li>';
					}
					$smcFunc['db_free_result']($result);
									
					echo '
						<ul>
					</div>
				</div>
				<div id="planet_commodities_frame">
					<div class="overlay"></div>
					<div id="planet_commodities_content">
						<h4>', $txt['bnt_planet_commodities'], '</h4>
						<ul>';
					
					if ($planetinfo['sells'] == 'N')
						{
						// Determine scan results for amount of ore on planet.					
						$roll = rand(1, 100);
						if ($roll < $success)
						{
							$sc_planet_ore = Number(round($planetinfo['ore'] * $sc_error / 100));
							echo '
										<li><span class="planet_status_title">', $txt['bnt_ore'], '</span><span class="planet_status_data"><span class="scan_success">', $sc_planet_ore, '</span></span></li>';
						}
						else
							echo '		
										<li><span class="planet_status_title">', $txt['bnt_ore'], '</span><span class="planet_status_data"><span class="scan_failure">', $txt['bnt_planet_scanfailed'], '</span></span></li>';
								
						// Determine scan results for amount of organics on planet.					
						$roll = rand(1, 100);
						if ($roll < $success)
						{
							$sc_planet_organics = Number(round($planetinfo['organics'] * $sc_error / 100));
							echo '
										<li><span class="planet_status_title">', $txt['bnt_organics'], '</span><span class="planet_status_data"><span class="scan_success">', $sc_planet_organics, '</span></span></li>';
						}
						else
							echo '		
										<li><span class="planet_status_title">', $txt['bnt_organics'], '</span><span class="planet_status_data"><span class="scan_failure">', $txt['bnt_planet_scanfailed'], '</span></span></li>';
						
								
						// Determine scan results for amount of goods on planet.					
						$roll = rand(1, 100);
						if ($roll < $success)
						{
							$sc_planet_goods = Number(round($planetinfo['goods'] * $sc_error / 100));
							echo '
										<li><span class="planet_status_title">', $txt['bnt_goods'], '</span><span class="planet_status_data"><span class="scan_success">', $sc_planet_goods, '</span></span></li>';
						}
						else
							echo '		
										<li><span class="planet_status_title">', $txt['bnt_goods'], '</span><span class="planet_status_data"><span class="scan_failure">', $txt['bnt_planet_scanfailed'], '</span></span></li>';
								
						// Determine scan results for amount of energy on planet.					
						$roll = rand(1, 100);
						if ($roll < $success)
						{
							$sc_planet_energy = Number(round($planetinfo['energy'] * $sc_error / 100));
							echo '
										<li><span class="planet_status_title">', $txt['bnt_energy'], '</span><span class="planet_status_data"><span class="scan_success">', $sc_planet_energy, '</span></span></li>';
						}
						else
							echo '		
										<li><span class="planet_status_title">', $txt['bnt_energy'], '</span><span class="planet_status_data"><span class="scan_failure">', $txt['bnt_planet_scanfailed'], '</span></span></li>';
					}
					else
						echo '
							<li><span class="planet_status_title">', $txt['bnt_ore'], '</span><span class="planet_status_data">', Number($planetinfo['ore']), '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_organics'], '</span><span class="planet_status_data">', Number($planetinfo['organics']), '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_goods'], '</span><span class="planet_status_data">', Number($planetinfo['goods']), '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_energy'], '</span><span class="planet_status_data">', Number($planetinfo['energy']), '</span></li>';
					
					echo'
						<ul>
					</div>
				</div>';
					
					UpdateTurns($playerinfo, $user_info);
				}			
				continue;
			
			// Player captures an empty planet
			case ($command == "capture" &&  $planetinfo['owner'] == 0):
				DisplayPlanetTitle($planetinfo);
				$commandresult = $txt['bnt_planet_captured'];
				
				// Update planet information to indicate planet has been captured
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_planets}
					SET corp = NULL,
						owner = {int:ship_id},
						base = "N",
						defeated = "N"
					WHERE planet_id = {int:planet_id}',
					array(
						'db_planets' => $dbtables['planets'],
						'ship_id' => $playerinfo['ship_id'],
						'planet_id' => $planet_id
					)
				);
				
				// Refresh planet information
				$result = $smcFunc['db_query']('', '
					SELECT *
					FROM {raw:db_planets}
					WHERE planet_id = {int:planet_id}',
					array(
						'db_planets' => $dbtables['planets'],
						'planet_id' => $planet_id
					)
				);
				$planetinfo = $smcFunc['db_fetch_assoc']($result);
				$smcFunc['db_free_result']($result);
				
				// Check sector ownership
				$ownership = calc_ownership($playerinfo['sector']);
				if (!empty($ownership))
					$commandresult .= ' - ' . $ownership;
					
				if ($planetinfo['owner'] != 0)
					gen_score($planetinfo['owner']);
				
				// Check if capture planet failed for some reason
				if ($planetinfo['owner'] == 0)
				{
					echo '
				<p>', $txt['bnt_planet_notcaptured'], '</p>';
					return;
				}
					
				playerlog($playerinfo['ship_id'], LOG_PLANET_CAPTURED, $planetinfo['colonists'] . '|' . $planetinfo['credits'] .'|' . $playerinfo['character_name']);
					
				DisplayOwnerMenu($planet_id, $planetinfo, $playerinfo, $commandresult);
				DisplayPlanetResources($planetinfo, $playerinfo, $playerinfo);				
				UpdateTurns($playerinfo, $user_info);
				continue;
			
			case ("capture" && ($planetinfo['owner'] == 0 || $planetinfo['defeated'] == 'Y')):
				DisplayPlanetTitle($planetinfo);
				echo '<p>', $txt['bnt_planet_notdef'], '</p>';
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_planets}
					SET defeated = "N"
					WHERE planet_id = {int:planet_id}',
					array(
						'db_planets' => $dbtables['planets'],
						'planet_id' => $planetinfo['planet_id']
					)
				);
				continue;
			
			default:
				echo '<p>', $txt['bnt_command_no'], '</p>';
		}
	}
}
// Else the planet is no longer there for whatever reason
else
	echo '<p>', $txt['bnt_planet_none'], '<p>';

	
function DisplayVistorMenu($planet_id, $planetinfo, $ownerinfo, $playerinfo, $commandresult = '')
{
	global $scripturl, $txt;
	global $sofa_on, $allow_ibank;
	
	// Determine per cent chance of success of scanning enemy planet - based on player's sensors and opponent's cloak.
	$success = (10 - $ownerinfo['cloak'] / 2 + $playerinfo['sensors']) * 5;
	if ($success < 5)
		$success = 5;
	if ($success > 95)
		$success = 95;
	
	echo '
				<p id="command_result">', $commandresult, '</p>
				<div id="planet_menu_frame">
					<div id="planet_menu_content">
						<h4>', $txt['bnt_planet_title'], '</h4>
						<ul>';
			
				if ($planetinfo['base'] == "Y" && $planetinfo['sells'] == "Y")
					echo '
							<li><span class="planet_menu_button" title="command=buy">', $txt['bnt_planet_buy_link'], '</span></li>';
			
				echo '
							<li><span class="planet_menu_button" title="command=scan">', $txt['bnt_planet_scn_link'], ' (', $success, '%)</span></li>
							<li><span class="planet_menu_button" title="command=attack"><input id="planet_dialog" type="hidden" value="Attack Planet" />', $txt['bnt_planet_att_link'], '</span></li>';
			
				if ($sofa_on)
					echo '
							<li><span class="planet_menu_button" title="command=bomb"><input id="planet_dialog" type="hidden" value="SOFA Attack Planet" />', $txt['bnt_sofa'], '</span>';
			
				if ($allow_ibank)
					echo '
							<li><a href="', $scripturl, '?action=blacknova;sa=igb;planet_id=', $planet_id, '">', $txt['bnt_igb_term'], '</a></li>';
			
				echo '
							<li><a href="', $scripturl, '?action=blacknova;sa=bounty">', $txt['bnt_by_title'], '</a></li>
						</ul>
					</div>
				</div>
				<div id="planet_dialog" class="dialog" title="Please Confirm"></div>';
}

function DisplayOwnerMenu($planet_id, $planetinfo, $playerinfo, $commandresult = '')
{
	global $scripturl, $txt;
	global $allow_ibank, $allow_genesis_destroy;
	
	echo '
				<p id="command_result">', $commandresult, '</p>
				<div id="planet_menu_frame">
					<div id="planet_menu_content">
						<h4>', $txt['bnt_planet_title'], '</h4>
						<ul>';
						
	if ($playerinfo['on_planet'] == 'Y' && $playerinfo['planet_id'] == $planet_id)
		echo '
							<li><span class="planet_menu_button" title="command=leave">', $txt['bnt_planet_leave_link'], '</span></li>';
	else
		echo '
							<li><span class="planet_menu_button" title="command=land">', $txt['bnt_planet_land_link'], '</span></li>';
							
	echo '
							<li><span class="planet_menu_button" title="command=transfer">', $txt['bnt_planet_transfer_link'], '</span></li>';
	
	if ($planetinfo['base'] == "Y")
		echo '
							<li><span class="planet_menu_button" title="command=sell">', $txt['bnt_planet_tsell'], '</span></li>';
	
	
	if ($planetinfo['base'] == "N")
		echo '
							<li><a href="', $scripturl, '?action=blacknova;sa=planet;planet_id=', $planet_id, ';command=base">', ucfirst($txt['bnt_planet_bbase_link']), '</a></li>';
							
	echo '
							<li><span class="planet_menu_button" title="command=changename"><input id="planet_dialog" type="hidden" value="Rename Planet" />', $txt['bnt_planet_changename'], '</span></li>';

	if ($playerinfo['ship_id'] == $planetinfo['owner'] && $playerinfo['team'] <> 0)
	{

		if ($planetinfo['corp'] == 0)
			echo '
							<li><a href="', $scripturl, '?action=blacknova;sa=corp;planet_id=' . $planet_id . ';plaction=planetcorp">', $txt['bnt_planet_mcorp_linkC'], '</a></li>';
		else
			echo '
							<li><a href="', $scripturl, '?action=blacknova;sa=corp;planet_id=' . $planet_id . ';plaction=planetpersonal">', $txt['bnt_planet_mcorp_linkP'], '</a></li>';
	}
	
	if ($allow_genesis_destroy) 
		echo '
							<li><span class="planet_menu_button" title="command=destroy"><input id="planet_dialog" type="hidden" value="Destroy Planet" />', $txt['bnt_planet_destroyplanet'], '</span></li>';
	
	if ($allow_ibank)
		echo '
							<li><a href="', $scripturl, '?action=blacknova;sa=igb;planet_id=', $planet_id, '">', $txt['bnt_igb_term'], '</a></li>';
			
	echo '
							<li><a href="', $scripturl, '?action=blacknova;sa=bounty">', $txt['bnt_by_title'], '</a></li>
						</ul>
					</div>
				</div>
				<div id="planet_dialog" class="dialog" title="Please Confirm"></div>';
}

function DisplayPlanetResources($planetinfo, $ownerinfo, $playerinfo)
{
	global $txt;
	
	echo '
			<div class="clearfix">
				<div id="planet_status_frame">
					<div class="overlay"></div>
					<div id="planet_status_content">
						<h4>', $txt['bnt_planet_status'], '</h4>
						<ul>
							<li><span class="planet_status_title">', $txt['bnt_planet_owner'], '</span><span class="planet_status_data">', $planetinfo['owner'] == 0 ? $txt['bnt_unowned'] : $ownerinfo['character_name'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_planet_base'], '</span><span class="planet_status_data">', $planetinfo['base'] == 'Y' ? $txt['bnt_yes'] : $txt['bnt_no'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_planet_selling'], '</span><span class="planet_status_data">', $planetinfo['sells'] == 'Y' ? $txt['bnt_yes'] : $txt['bnt_no'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_credits'], '</span><span class="planet_status_data">', $playerinfo['user_id'] == $ownerinfo['user_id'] ? Number($planetinfo['credits']) : $txt['bnt_unknown'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_colonists'], '</span><span class="planet_status_data">', $playerinfo['user_id'] == $ownerinfo['user_id'] ? Number($planetinfo['colonists']) : $txt['bnt_unknown'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_fighters'], '</span><span class="planet_status_data">', $playerinfo['user_id'] == $ownerinfo['user_id'] ? Number($planetinfo['fighters']) : $txt['bnt_unknown'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_torps'], '</span><span class="planet_status_data">', $playerinfo['user_id'] == $ownerinfo['user_id'] ? Number($planetinfo['torps']) : $txt['bnt_unknown'], '</span></li>
						<ul>
					</div>
				</div>
				<div id="planet_commodities_frame">
					<div class="overlay"></div>
					<div id="planet_commodities_content">
						<h4>', $txt['bnt_planet_commodities'], '</h4>
						<ul>
							<li><span class="planet_status_title">', $txt['bnt_ore'], '</span><span class="planet_status_data">', ($playerinfo['user_id'] == $ownerinfo['user_id'] || $planetinfo['sells'] == 'Y') ? Number($planetinfo['ore']) : $txt['bnt_unknown'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_organics'], '</span><span class="planet_status_data">', ($playerinfo['user_id'] == $ownerinfo['user_id'] || $planetinfo['sells'] == 'Y') ? Number($planetinfo['organics']) : $txt['bnt_unknown'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_goods'], '</span><span class="planet_status_data">', ($playerinfo['user_id'] == $ownerinfo['user_id'] || $planetinfo['sells'] == 'Y') ? Number($planetinfo['goods']) : $txt['bnt_unknown'], '</span></li>
							<li><span class="planet_status_title">', $txt['bnt_energy'], '</span><span class="planet_status_data">', ($playerinfo['user_id'] == $ownerinfo['user_id'] || $planetinfo['sells'] == 'Y') ? Number($planetinfo['energy']) : $txt['bnt_unknown'], '</span></li>
						<ul>
					</div>
				</div>
			</div>';
			
	// Display the production change table, should be a close match to what is found in planet_report.php
	// All processing of changes is handled by planet report functions.
	if ($planetinfo['owner'] != 0 && $playerinfo['user_id'] == $ownerinfo['user_id'] && $planetinfo['base'] == "Y")
	{
		// Next block of echo's creates the header of the table.
		echo '
		<script type="text/javascript">
			$(document).ready(function(){
				// Table sorting function
				$("#planet_production_table").tablesorter({
					headers: { 
						0: {sorter: false}
					},
					widgets: ["zebra"]
				});
				// Check for planets with global production enabled
				$(".global_toggle").each( function () {
					if ($(this).attr("checked"))
					{
						var planet_id = $(this).attr("name");
						$("." + planet_id).attr("disabled", true);
						$("." + planet_id).addClass("bnt_disabled");
					}
				});
				// Global production check all checkbox
				$("#global_production_checkall").toggle(
					function () {
						$(":checkbox").attr("checked", true);
						$("input[class^=\'global_toggle_\']").attr("disabled", true);
						$("input[class^=\'global_toggle_\']").addClass("bnt_disabled");
					},
					function () {
						$(":checkbox").removeAttr("checked");
						$("input[class^=\'global_toggle_\']").removeAttr("disabled");
						$("input[class^=\'global_toggle_\']").removeClass("bnt_disabled");
				});
				// OnChange updates for production values 
				$("input:text").change( function() {
					$.update_row = {
						planet_id: $(this).closest("tr").attr("id"),
						credits: 0
					}
					$(".global_toggle_" + $.update_row.planet_id).each(function() {
						$.update_row.credits = $.update_row.credits + ($(this).val() - 0);
					});
					$("#credits_" + $.update_row.planet_id).html((100 - $.update_row.credits) + "%");
				});
			});
		</script>
		<table id="planet_production_table" class="bnt_table">
			<thead>
				<tr>
					<th colspan="8" align="center">', $txt['bnt_pr_planetsettings'], '</th>
				</tr>
			</thead>
			<tbody>
				<tr class="second_header">
					<td id="global_production_checkall">', $txt['bnt_pr_global'], '</td>
					<td>', $txt['bnt_ore'], '</td>
					<td>', $txt['bnt_organics'], '</td>
					<td>', $txt['bnt_goods'], '</td>
					<td>', $txt['bnt_energy'], '</td>
					<td>', $txt['bnt_fighters'], '</td>
					<td>', $txt['bnt_torps'], '</td>
					<td>', $txt['bnt_credits'], '</td>
				</tr>';

		echo '
				<tr id="', $planetinfo['planet_id'], '">
					<td><input type="checkbox" style="check" class="global_toggle" name="global_toggle_', $planetinfo['planet_id'], '" ';
			
		if ($planetinfo['prod_global'] == 'Y')
			echo 'checked="yes"';

		echo ' /></td>
					<td><input type="text" class="global_toggle_', $planetinfo['planet_id'], '" name="prod_ore" maxlength="3" value="', $planetinfo['prod_ore'], '" />%</td>
					<td><input type="text" class="global_toggle_', $planetinfo['planet_id'], '" name="prod_organics" maxlength="3" value="', $planetinfo['prod_organics'], '" />%</td>
					<td><input type="text" class="global_toggle_', $planetinfo['planet_id'], '" name="prod_goods" maxlength="3" value="', $planetinfo['prod_goods'], '" />%</td>
					<td><input type="text" class="global_toggle_', $planetinfo['planet_id'], '" name="prod_energy" maxlength="3" value="', $planetinfo['prod_energy'], '" />%</td>
					<td><input type="text" class="global_toggle_', $planetinfo['planet_id'], '" name="prod_fighters" maxlength="3" value="', $planetinfo['prod_fighters'], '" />%</td>
					<td><input type="text" class="global_toggle_', $planetinfo['planet_id'], '" name="prod_torp" maxlength="3" value="', $planetinfo['prod_torp'], '" />%</td>';
			
		$planet_credits = 100 - ($planetinfo['prod_ore'] + $planetinfo['prod_organics'] + $planetinfo['prod_goods'] + $planetinfo['prod_energy'] + $planetinfo['prod_fighters'] + $planetinfo['prod_torp']);
		
		echo '
					<td id="credits_', $planetinfo['planet_id'], '">', $planet_credits, '%</td>
				</tr>';
		
		echo '
			</tbody>
		</table>
		<div id="planet_button_frame"><span id="change_production" class="bnt_button ui-state-default ui-corner-all">', $txt['bnt_pr_change'], '</span></div>';
	}
}

function UpdateTurns($playerinfo, $user_info)
{
	global $smcFunc;
	global $dbtables;

	// Update player turns
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET turns = turns - 1,
			turns_used = turns_used + 1
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_id' => $playerinfo['ship_id']
		)
	);
	
	// Refresh player turns.
	$result = $smcFunc['db_query']('', '
		SELECT turns, turns_used
		FROM {raw:db_ships}
		WHERE user_id = {int:user_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'user_id' => $user_info['id'],
		)
	);
	$turns = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	echo '
				<input id="updated_turns_available" type="hidden" value="', Number($turns['turns']), '">
				<input id="updated_turns_used" type="hidden" value="', Number($turns['turns_used']), '">';
}

/*
	Display the title area differently depending on whether the planet is named
	and whether the player is in orbit or landed on the planet.
*/
function DisplayPlanetTitle($planetinfo)
{	
	global $txt;
	
	if (empty($planetinfo['name']))
		BigTitle($txt['bnt_unnamed'] . ' ' . $txt['bnt_planet']);
	else
		BigTitle($planetinfo['name']);
}

?>
